// Package cmd /*
package cmd

import (
	"github.com/spf13/cobra"
	"log"
	"remote_exec/goterm/term"
	"remote_exec/util"
)

var encCmd = &cobra.Command{
	Use:     "enc [flags]",
	Short:   "encrypt config file",
	Long:    "encrypt config file",
	Example: "remote enc",
	Run: func(cmd *cobra.Command, args []string) {
		var (
			err           error
			config        *util.Config
			configPath, _ = cmd.Flags().GetString(util.ConstConfig)
			isDecrypt, _  = cmd.Flags().GetBool(util.ConstIsDecrypt)
			operateMode   = util.ConstEncMode
			passwd        string
		)
		if config, err = util.ParseConfig(configPath); err != nil {
			log.Println(term.Redf(err.Error()))
			return
		}
		if isDecrypt {
			// Dec
			operateMode = util.ConstDecMode
			if !config.IsEncrypt {
				return
			}
			if passwd, err = util.InputPasswd(); err != nil {
				log.Println(term.Redf("an error occurred in input the password."))
				return
			}
			if err := config.DecryptConfig(passwd); err != nil {
				log.Println(term.Redf("password is error, decrypt config failed."))
				return
			}
		} else {
			// Enc
			operateMode = util.ConstEncMode
			if config.IsEncrypt {
				return
			}
			if passwd, err = util.SetPasswd(); err != nil {
				log.Println(term.Redf("an error occurred in set the password."))
				return
			}
			if err := config.EncryptConfig(passwd); err != nil {
				log.Println(term.Redf("encrypt config failed."))
				return
			}
		}
		if err = config.WriteConfig(configPath); err != nil {
			log.Println(term.Redf(err.Error()))
			return
		}

		log.Println(term.Greenf("%v config finished.", operateMode))
	},
}

func init() {
	encCmd.PersistentFlags().BoolP(util.ConstIsDecrypt, "d", false, "decrypt config")
	rootCmd.AddCommand(encCmd)
}
